﻿using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Fields;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Processing;
using SkiaSharp;
using System;
using System.Drawing.Imaging;
using ZXing;
using ZXing.QrCode;

namespace Huasky.MyWrod.Application.Word;

/// <summary>
/// word操作
/// </summary>
/// <param name="logger"></param>
[ApiRoute.App("word")]
public class WordController(ILogger<WordController> logger)
{
    public ILogger<WordController> Logger { get; } = logger;

    /// <summary>
    /// 生成PDF
    /// </summary>
    /// <returns></returns>
    [HttpGet("genarate")]
    public string Genarate()
    {
        var filepath = @".\Source\测试通知书.docx";
        var savepath = @".\Source\测试通知书2.pdf";

        var doc = new Document(filepath);
        var builder = new DocumentBuilder(doc);

        var fileds = doc.Range.Fields.Where(a => a.Type == FieldType.FieldHyperlink)
                        .Cast<FieldHyperlink>()
                        .Where(a => a.Address.StartsWith("doc://", true, null))
                        .ToList();

        fileds.ForEach(link =>
        {
            if (link.Address != "doc://text/Report.ApproveDoctor") return;
            link.Result = "孙小双";
            link.Unlink();
        });

        fileds.ForEach(link =>
        {
            if (link.Address != "doc://text/Report.SubmitDoctor") return;
            var picpath = @".\Source\sign.png";
            builder.MoveTo(link.Start);
            using var bitmap = SKBitmap.Decode(File.ReadAllBytes(picpath));
            var rate = bitmap.Height / 14.0;
            builder.InsertImage(bitmap, (int)(bitmap.Width / rate), (int)(bitmap.Height / rate));
            link.Remove();
        });

        fileds.ForEach(a =>
        {
            if (a.Address == "doc://text/Report.ApproveDoctor") return;
            a.Remove();
        });

        doc.Save(savepath, SaveFormat.Pdf);

        return "创建成功";
    }


    /// <summary>
    /// 生成带图的PDF
    /// </summary>
    /// <returns></returns>
    [HttpGet("genarate2")]
    public string Genarate2()
    {
        var filepath = @".\Source\a.docx";
        var savepath = @".\Source\image.pdf";

        var doc = new Document(filepath);
        var builder = new DocumentBuilder(doc);

        var fileds = doc.GetChildNodes(NodeType.Shape, true)
                   .Cast<Shape>()
                   .Where(i => i.ShapeType == ShapeType.Image)
                   .Where(i => i.HRef.StartsWith("doc://", true, null))
                   .ToList();

        fileds.ForEach(image =>
        {
            var width = (int)image.Width;
            var height = (int)image.Height;
            if (image.HRef.Contains("doc://image/ReportImage1"))
            {
                // 普通图片
                var buffer = File.ReadAllBytes(@".\Source\good.png");
                var source = Resize(buffer, width, height, "Uniform");
                insert(image, buffer, width, height);
            }
            else if (image.HRef.Contains("doc://image/ReportImage2"))
            {
                // 条形码
                var source = GenerateCodeImage(BarcodeFormat.CODE_128, "123456abc", width, height);
                insert(image, source, width, height);
            }
            else if (image.HRef.Contains("doc://image/ReportImage3"))
            {
                // 二维码
                var source = GenerateCodeImage(BarcodeFormat.QR_CODE, "http://e.jiandanmao.cn", width, height);
                insert(image, source, width, height);
            }
            else
            {
                image.Remove();
            }
        });

        doc.Save(savepath, SaveFormat.Pdf);

        return "创建成功";

        void insert(Shape image, byte[] source, int width, int height)
        {
            image.HRef = "";
            builder.MoveTo(image);
            builder.InsertImage(source, image.RelativeHorizontalPosition,
                                        image.Left,
                                        image.RelativeVerticalPosition,
                                        image.Top,
                                        image.Width,
                                        image.Height,
                                        image.WrapType);
            image.Remove();
        }
    }

    // 调整图片大小
    byte[] Resize(byte[] source, int nWidth, int nHeight, string stretchType)
    {
        using var image = Image.Load(source);

        image.Mutate(i => i.Resize(new ResizeOptions()
        {
            Size = new Size(nWidth, nHeight),
            Mode = getResizeMode(),
        }));

        using var buffer = new MemoryStream();
        image.SaveAsPng(buffer);
        return buffer.ToArray();

        ResizeMode getResizeMode()
        {
            switch (stretchType?.ToLower())
            {
                case "fill":
                    //不保持比例填充目标
                    return ResizeMode.Stretch;

                case "uniformtofill":
                    ////保持比例填充目标
                    return ResizeMode.Crop;

                default:
                    //保持比例尽量缩放到目标大小， uniform模式（目标尺寸， 无内容地方为空白）
                    return ResizeMode.BoxPad;
            }

            //ResizeMode.Max   保持比例尽量缩放到目标大小, 源图片比例， 不是目标尺寸
        }
    }

    // 生成条形码/二维码
    byte[] GenerateCodeImage(BarcodeFormat format, string text, int width, int height)
    {
        var writer = new BarcodeWriter
        {
            Format = format
        };

        var options = new QrCodeEncodingOptions
        {
            DisableECI = true,
            CharacterSet = "UTF-8",
            PureBarcode = true,
            Height = height,
            Width = width,
            Margin = 1
        };
        //设置内容编码
        //设置二维码的宽度和高度
        //设置二维码的边距,单位不是固定像素
        writer.Options = options;

        using var bmp = writer.Write(text);
        using var buffer = new MemoryStream();

        bmp.Save(buffer, ImageFormat.Png);
        return buffer.ToArray();
    }


}
